<?php
	require("Util.php");
	require("NonTextUpload.php");
	require("TextUpload.php");
		
	$stat = processFiles();
	echo $stat;
	
	/*
		Process all the file inside the unprocessed folder
		@return string $toFile message
	*/
	function processFiles() {
		$folder_name = $_POST["templateFile"];
		$unproc_name = "bookdir/".$folder_name."/unprocessed";
		$toFile = "";
		$res = "no error";
	
		if ($handle = opendir($unproc_name)) {
    	while (false !== ($file = readdir($handle))) {
     		$dir = "bookdir/".$folder_name."/".$file;
      		if((strcmp($file,".") != 0) && (strcmp($file,"..") != 0)) {
					if (!is_dir($dir)) {
						$tmpFile = uploadFile($file);
						if ($tmpFile == 0) {
							if (strcmp(strtolower($_POST["newBook"]),"true") == 0) {
								$txtFile = "Wikifying the book";
							} else {
								$txtFile = "Finish uploading the file ".$file;
							}
						} else {
							$res = "error";
							if ($tmpFile == 1) {
								$txtFile = "Cannot upload the file ".$file." because of permission error";
							} else {
								$txtFile =  "Cannot upload the file ".$file." because file format is not recognized by flash"; 
							}
						}
						$toFile .= $txtFile;
					}
				}
    		}
			closedir($handle);
		}
		$param = "&msg=".$toFile."&result=".$res;
		return $param;
	}
	
	/*
		Create the index.html file
		@param string $folder_name the directory path to the template file
		@param string $dir_name the name of the template file
	*/
	function createIndex($folder_name,$dir_name) {
		
		//create the index.html
		$index_input = "<html>\n<head>\n";
		$index_input .= "<title>".$dir_name."</title>\n";
		$index_input .= "<script src='RealisticBook.js' language='javascript'></script>\n</head>\n";
		$index_input .= "<body>\n";
		$index_input .= "<!-- You have to have this div tag with id = bookdiv in your HTML file!! This is where the program will be embedded -->\n";
		$index_input .= "<div id='bookdiv'></div>\n";
		$index_input .= "<script type='text/javascript'>\n";
		$index_input .= "<!-- \n";
		$index_input .= " embedBookProgram(new Array('".$GLOBALS["wikibook"]."'));\n";
		$index_input .= "// -->\n";
		$index_input .= "</script>\n";
		$index_input .= "<noscript>\n";
		$index_input .= " This content requires JavaScript and Adobe Flash Player.\n";
		$index_input .= " <a href='http://www.macromedia.com/go/getflash/'>Get Flash</a>\n";
		$index_input .= "</noscript>\n</body>\n</html>\n";

		$index_file = "index.html";
		$file = modifyFile($folder_name."/".$index_file,"w");
		if (!$file) die ("cannot open the file");
		fwrite($file, $index_input);
		fclose($file);
	}
	
	/*
		Convert string to its boolean value
		@param string $str the string
	*/
	function strtobool ($str) {
		$f = false;
		if (strcmp(strtolower($str),"true") == 0) {
			$f = true;
		}
		return $f;
	}
	
	/*
		Upload the selected file to the repository area
		@param string $filedata the path to the file 
	*/
	function uploadFile($filedata) {
		$file_ext = end(explode(".", strtolower($filedata)));
		$allowedExtension = array("pdf","html","htm","xml","txt","flv","mp3","png","swf","jpg");
		if (in_array($file_ext, $allowedExtension)) {
			$isTemplate = false;
			$forceSynonym = strtobool($_POST["newBook"]);
			$forceReplace = strtobool($_POST["newVersion"]);
			$forceIndex = strtobool($_POST["newIndex"]);
			$isImage = strtobool($_POST["isImage"]);
			$folder_name = $_POST["templateFile"];
			
			$filename = strtolower(basename($filedata));
			
			if (!file_exists($GLOBALS['uploaddir']."/".$folder_name."/".$GLOBALS["book"])) {
					$isTemplate = true;
			}
			
			$folderpath = $GLOBALS['uploaddir']."/".$folder_name;
			$filename = getValidFilename($GLOBALS['uploaddir']."/".$folder_name, $allowedExtension, $filename, $forceReplace);
			$uploadfile = $folderpath."/".$filename;//path for the input file
			copy($folderpath."/unprocessed/".$filedata,$uploadfile);
			
			if (file_exists($uploadfile)) {
				unlink($folderpath."/unprocessed/".$filedata);
				$media_ext = array("flv","mp3");
				$image_ext = array("swf","png","jpg");
				if ((strcmp($file_ext,"pdf") == 0) || (in_array($file_ext, $media_ext)) || (in_array($file_ext, $image_ext))) {
					//we need to create page images
					$dir_name = $GLOBALS['uploaddir']."/".$folder_name."/repository";//path to the repository
					$result = array();
					if (strcmp($file_ext,"pdf") == 0) {
						$result = convertPDF($dir_name,$uploadfile, !$isImage, false);//$isSWF, $txtSWF);
					} else if (in_array($file_ext, $media_ext)) {
						$result = convertMedia($dir_name,$uploadfile);
					} else if (in_array($file_ext, $image_ext)) {
						$result = convertImage($dir_name,$uploadfile);
					}

					if ($isTemplate == true)  {//generate template file
						createTemplate($folderpath,$folder_name,$result,$isImage);
					} else {
						appendTemplateMedia($folderpath, $result,$isImage);
					}
				} else {//it's a text file, we need to tidy and fix the image path first
					convertText($folderpath,$uploadfile);
					
					if ($isTemplate == true)  {//generate template file
						copy($uploadfile, $folderpath."/".$GLOBALS["book"]);
					} else {
						appendTemplateText($folderpath, $uploadfile);
					}
					
					//move the file to the repository
					copy($uploadfile, $folderpath."/repository/".$filename);
					unlink($uploadfile);
				}
				
				if (($isTemplate == true) || ($forceIndex == true)) {//generate index file
					createIndex($folderpath,$folder_name);
				}
				
				//copy the appended template to the wikified template
				$bookfile = $folderpath."/".$GLOBALS["book"];//path for the input file
				$wikifile = $folderpath."/".$GLOBALS["wikibook"];//path for the wikified file
				copy($bookfile,$wikifile);
				                                            
				$toFile = "<p>Uploaded files:</p>\n";
				$toFile = listFiles ($folderpath."/repository/", $toFile);
				
				$process_file = "processed.htm";
				$pfile = modifyFile($folderpath."/".$process_file,"w");
				if (!$pfile) die ("cannot open the file");
				fwrite($pfile, $toFile);
				fclose($pfile);
				return 0;
			}
			return 1;
		}
		
		return 2; 
	}
?>